import { App, createApp, onUnmounted } from 'vue';
import FOverlay from './overlay.component';

export interface OverlayServiceOptions {
    host: any;
    popupPosition?: { left: number; top: number };
    content?: { render(): JSX.Element };
    render?(): any;
    onClickCallback?(): void;
}

function getContentRender(props: OverlayServiceOptions) {
    if (props.content && props.content.render) {
        return props.content.render;
    }
    if (props.render && typeof props.render === 'function') {
        return props.render;
    }
}

function createOverlayInstance(options: OverlayServiceOptions): App {
    const container = document.createElement('div');
    container.style.display = 'contents';
    let overlayApp: App;
    const onClickCallback = options.onClickCallback || (() => { });
    const onClose = () => {
        onClickCallback();
        if (overlayApp) {
            overlayApp.unmount();
        }
    };
    overlayApp = createApp({
        setup() {
            onUnmounted(() => {
                document.body.removeChild(container);
            });
            const contentRender = getContentRender(options);
            return () => (
                <FOverlay popup-content-position={options.popupPosition} host={options.host} onClick={onClose}>
                    {contentRender && contentRender()}
                </FOverlay>
            );
        }
    });
    document.body.appendChild(container);
    overlayApp.mount(container);
    return overlayApp;
}

export default class OverylayService {

    static show(options: OverlayServiceOptions): App {
        return createOverlayInstance(options);
    }
}
